package com.api.interceptor;

import cn.hutool.core.util.StrUtil;
import com.api.annotation.Login;
import com.api.common.exception.MySystemException;
import com.api.common.utils.ThreadLocalUtil;
import com.api.entity.Token;
import com.api.service.TokenService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Resource
    private TokenService tokenService;

    public static final String USER_KEY = "userId";

    //创建登录身份校验拦截器
    @Override  //请求开始前触发的拦截方法
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Login annotation;

        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }
        if (annotation == null) {
            return true;
        }
        //从header中获取token
        String token = request.getHeader("Authorization");
        //如果header中不存在token，则从参数中获取token
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("Authorization");
        }
        //token为空
        if (StrUtil.isBlank(token)) {
            throw new MySystemException(401,"登录失效");
        }

        //查询token信息
        Token tokenEntity = tokenService.getByToken(token);
        System.out.println(tokenEntity);
        if (tokenEntity == null || tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) {
            throw new MySystemException(401,"登录失效");
        }
        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, tokenEntity.getUserId());
        System.out.println(request.getAttribute(USER_KEY));
        return true;
    }

    @Override  //请求完成后触发的拦截方法
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)  {
        //清空ThreadLocal中的数据防止内存泄漏
        ThreadLocalUtil.remove();
    }


}
